<?php namespace Phpcmf\Model\Huiyuan;

class Search extends \Phpcmf\Model {

    // 初始化搜索主表
    public function init($table) {
        $this->mytable = 'member';
        return $this;
    }

    // 获取搜索参数
    public function get_param($config) {

        $get = $_GET;
        $get = isset($get['rewrite']) ? dr_search_rewrite_decode($get['rewrite'], null) : $get;
        $get && $get = \Phpcmf\Service::L('input')->xss_clean($get);

        $get['s'] = $get['c'] = $get['m'] = $get['id'] = null;
        unset($get['s'], $get['c'], $get['m'], $get['id']);
        if (!$get && IS_API_HTTP) {
            $get = \Phpcmf\Service::L('input')->xss_clean($_POST);
        }

        $_GET['page'] = $get['page'];
        $get['keyword'] = dr_get_keyword($get['keyword']);

        $catid = (int)$get['groupid'];

        return [$catid, $get];
    }


    /**
     * 查询数据并设置缓存
     */
    public function get_user_data($config, $get, $groupid) {

        // 模块表名称
        $table = $this->dbprefix($this->mytable);
        $table_data = $this->dbprefix($this->mytable.'_data');

        // 排序查询参数
        ksort($get);
        $param = $get;
        $get['order'] = $get['page'] = null;
        unset($get['order'], $get['page']);

        // 查询缓存
        $id = md5($table.dr_array2string($get));
        if (SYS_CACHE_SEARCH) {
            $data = $this->db->table($this->mytable.'_search')->where('id', $id)->get()->getRowArray();
            $time = intval(SYS_CACHE_SEARCH) * 3600;
            if ($data && $data['inputtime'] < SYS_TIME - $time) {
                $data = [];
            }
            $this->db->table($this->mytable.'_search')->where('inputtime <'. (SYS_TIME - $time))->delete();
        } else {
            $data = [];
            $this->db->table($this->mytable.'_search')->where('inputtime <'. (SYS_TIME - 3600))->delete();
        }

        // 缓存不存在重新入库更新缓存
        if (!$data) {

            $get['keyword'] = $get['groupid'] = null;
            unset($get['keyword'], $get['groupid']);

            // 主表的字段
            $field = \Phpcmf\Service::L('cache')->get('table-'.SITE_ID, $table);
            if (!$field) {
                return dr_return_data(0, dr_lang('主表【%s】字段不存在', $table));
            }
            $field_data = \Phpcmf\Service::L('cache')->get('table-'.SITE_ID, $table_data);
            if (!$field_data) {
                return dr_return_data(0, dr_lang('自定义表【%s】字段不存在', $table_data));
            }

            // 默认搜索条件
            $where = [];

            // 按用户组
            if ($param['groupid'] != '') {
                $where[] = '`'.$table.'`.`id` IN (SELECT `uid` FROM `'.$table.'_group_index` WHERE gid='.intval($param['groupid']).')';
            }

            // 关键字匹配条件
            if ($param['keyword'] != '') {
                $temp = [];
                $sfield = $config['search']['kw'] ? $config['search']['kw'] : explode(',',  'name,username');
                $search_keyword = trim(str_replace([' ', '_'], '%', dr_safe_replace($param['keyword'])), '%');
                if ($sfield) {
                    foreach ($sfield as $t) {
                        if ($t) {
                            if (in_array($t, $field)) {
                                $temp[] = '`'.$table.'`.`'.$t.'` LIKE "%'.$search_keyword.'%"';
                            } elseif (in_array($t, $field_data)) {
                                $temp[] = '`'.$table_data.'`.`'.$t.'` LIKE "%'.$search_keyword.'%"';
                            }
                        }
                    }
                }
                $where[] = $temp ? '('.implode(' OR ', $temp).')' : '`'.$table.'`.`title` LIKE "%'.$search_keyword.'%"';
            }
            // 字段过滤
            foreach (\Phpcmf\Service::C()->member_cache['field'] as $name => $field) {
                if (isset($get[$name]) && dr_strlen($get[$name])) {
                    $where[] = $this->_where($table_data, $name, $get[$name], $field);
                }
            }

            // 筛选空值
            foreach ($where as $i => $t) {
                if (dr_strlen($t) == 0) {
                    unset($where[$i]);
                }
            }

            $where = $where ? 'WHERE '.implode(' AND ', $where) : '';

            // 最大数据量
            $limit = (int)$config['search']['total'] ? ' LIMIT '.(int)$config['search']['total'] : '';

            // 组合sql查询结果
            $sql = "SELECT `{$table}`.`id` FROM `".$table."` LEFT JOIN `".$table_data."` ON `".$table."`.id=`".$table_data."`.id {$where} ORDER BY id ".$limit;

            // 重新生成缓存文件
            $result = $this->db->query($sql)->getResultArray();
            if ($result) {
                $cid = [];
                // 删除旧数据
                $this->db->table($this->mytable.'_search')->where('id', $id)->delete();
                // 入库索引表
                foreach ($result as $t) {
                    $cid[] = $t['id'];
                }
                // 缓存入库
                $data = [
                    'id' => $id,
                    'groupid' => $groupid,
                    'params' => dr_array2string(['param' => $param, 'sql' => $sql]),
                    'keyword' => $param['keyword'] ? $param['keyword'] : '',
                    'contentid' => $this->dbprefix('member.id in('.($limit ? @implode(',', $cid) : $sql).')'),
                    'inputtime' => SYS_TIME
                ];
                $this->db->table($this->mytable.'_search')->replace($data);
            } else {
                $data = [
                    'id' => $id,
                    'groupid' => $groupid,
                    'params' => dr_array2string(['param' => $param, 'sql' => $sql]),
                    'keyword' => $param['keyword'] ? $param['keyword'] : '',
                    'contentid' => $this->dbprefix('member.id=0'),
                ];
            }
        } else {
            $this->db->table($this->mytable.'_search')->where('id', $data['id'])->update([
                'inputtime' => SYS_TIME
            ]);
        }

        // 格式化值
        $p = dr_string2array($data['params']);
        $data['sql'] = $p['sql'];
        $data['params'] = $p['param'];
        $groupid && $data['params']['groupid'] = $groupid;
        $data['params']['order'] = $param['order']; // order 参数不变化

        return $data;
    }
}
